package com.huaju.enity;

import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.hibernate.LockOptions;
import org.hibernate.Query;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.hibernate.SessionFactory;

import static org.hibernate.criterion.Example.create;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.transaction.annotation.Transactional;

/**
 * A data access object (DAO) providing persistence and search support for
 * Incomelist entities. Transaction control of the save(), update() and delete()
 * operations can directly support Spring container-managed transactions or they
 * can be augmented to handle user-managed Spring transactions. Each of these
 * methods provides additional information for how to configure it for the
 * desired type of transaction control.
 * 
 * @see com.huaju.enity.Incomelist
 * @author MyEclipse Persistence Tools
 */
@Transactional
public class IncomelistDAO {
	private static final Logger log = LoggerFactory
			.getLogger(IncomelistDAO.class);
	// property constants
	public static final String IDESC = "idesc";
	public static final String IMONEY = "imoney";
	public static final String SUCCESS = "success";

	private SessionFactory sessionFactory;

	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}

	private Session getCurrentSession() {
		return sessionFactory.getCurrentSession();
	}

	protected void initDao() {
		// do nothing
	}

	public void save(Incomelist transientInstance) {
		log.debug("saving Incomelist instance");
		try {
			getCurrentSession().save(transientInstance);
			log.debug("save successful");
		} catch (RuntimeException re) {
			log.error("save failed", re);
			throw re;
		}
	}
	public void saveOrUpdate(Incomelist transientInstance) {
		log.debug("saving Incomelist instance");
		try {
			getCurrentSession().saveOrUpdate(transientInstance);
			log.debug("save successful");
		} catch (RuntimeException re) {
			log.error("save failed", re);
			throw re;
		}
	}

	public void delete(Incomelist persistentInstance) {
		log.debug("deleting Incomelist instance");
		try {
			getCurrentSession().delete(persistentInstance);
			log.debug("delete successful");
		} catch (RuntimeException re) {
			log.error("delete failed", re);
			throw re;
		}
	}
	
	public Double getAllIncomeByUser(Integer id) {
		log.debug("finding all Incomelist instances");
		try {
			String queryString = " SELECT Sum(imoney) FROM incomelist  where aid ="+id;
			SQLQuery queryObject = getCurrentSession().createSQLQuery(queryString);
			if(queryObject.list()!=null)
			{
				try {
					return Double.parseDouble(queryObject.list().get(0).toString());
				} catch (Exception e) {
					return 0.00;
				}
				
			}
			return 0.00;
		} catch (RuntimeException re) {
			log.error("find all failed", re);
			throw re;
		}
	}

	public Incomelist findById(java.lang.Integer id) {
		log.debug("getting Incomelist instance with id: " + id);
		try {
			Incomelist instance = (Incomelist) getCurrentSession().get(
					"com.huaju.enity.Incomelist", id);
			return instance;
		} catch (RuntimeException re) {
			log.error("get failed", re);
			throw re;
		}
	}
	
	
	public List findTotalAnalysis(Integer comId ,String month) {
		try {
			String queryString = "select count(*),sum(imoney) from incomelist where successTime > ?";
			if (comId != null) {
				queryString += " and comId="+ comId;
			}
			SQLQuery queryObject = getCurrentSession().createSQLQuery(
					queryString);
			queryObject.setParameter(0, month);
			return queryObject.list();
		} catch (RuntimeException re) {
			log.error("find by property name failed", re);
			throw re;
		}
	}
	
	public Integer countAll(String pro,Object value) {
		log.debug("finding all bankcard instances");
		try {
			String queryString = "from Incomelist model where model."+pro+"=?";
			Query queryObject = getCurrentSession().createQuery(queryString);
			queryObject.setParameter(0, value);
			return queryObject.list().size();
		} catch (RuntimeException re) {
			log.error("find all failed", re);
			throw re;
		}
	}
	
	
	public List findByPage(Integer start,Integer size,String pro,Object value) {
		log.debug("finding all bankcard instances");
		try {
			String queryString = "from Incomelist model where model."+pro+"=? order by iid desc";
			Query queryObject = getCurrentSession().createQuery(queryString);
			queryObject.setParameter(0, value);
			queryObject.setMaxResults(size);
			queryObject.setFirstResult(start);
			
			return queryObject.list();
		} catch (RuntimeException re) {
			log.error("find all failed", re);
			throw re;
		}
	}

	public List<Incomelist> findByExample(Incomelist instance) {
		log.debug("finding Incomelist instance by example");
		try {
			List<Incomelist> results = (List<Incomelist>) getCurrentSession()
					.createCriteria("com.huaju.enity.Incomelist")
					.add(create(instance)).list();
			log.debug("find by example successful, result size: "
					+ results.size());
			return results;
		} catch (RuntimeException re) {
			log.error("find by example failed", re);
			throw re;
		}
	}

	public List findByProperty(String propertyName, Object value) {
		log.debug("finding Incomelist instance with property: " + propertyName
				+ ", value: " + value);
		try {
			String queryString = "from Incomelist as model where model."
					+ propertyName + "= ?";
			Query queryObject = getCurrentSession().createQuery(queryString);
			queryObject.setParameter(0, value);
			return queryObject.list();
		} catch (RuntimeException re) {
			log.error("find by property name failed", re);
			throw re;
		}
	}

	public List<Incomelist> findByIdesc(Object idesc) {
		return findByProperty(IDESC, idesc);
	}

	public List<Incomelist> findByImoney(Object imoney) {
		return findByProperty(IMONEY, imoney);
	}

	public List<Incomelist> findBySuccess(Object success) {
		return findByProperty(SUCCESS, success);
	}

	public List findAll() {
		log.debug("finding all Incomelist instances");
		try {
			String queryString = "from Incomelist";
			Query queryObject = getCurrentSession().createQuery(queryString);
			return queryObject.list();
		} catch (RuntimeException re) {
			log.error("find all failed", re);
			throw re;
		}
	}
	
	public Integer countAll() {
		log.debug("finding all Incomelist instances");
		try {
			String queryString = "from Incomelist";
			Query queryObject = getCurrentSession().createQuery(queryString);
			return queryObject.list().size();
		} catch (RuntimeException re) {
			log.error("find all failed", re);
			throw re;
		}
	}
	public List findByPage(Integer start,Integer size) {
		log.debug("finding all Incomelist instances");
		try {
			String queryString = "from Incomelist order by iid desc";
			Query queryObject = getCurrentSession().createQuery(queryString);
			queryObject.setMaxResults(size);
			queryObject.setFirstResult(start);
			
			return queryObject.list();
		} catch (RuntimeException re) {
			log.error("find all failed", re);
			throw re;
		}
	}

	public Incomelist merge(Incomelist detachedInstance) {
		log.debug("merging Incomelist instance");
		try {
			Incomelist result = (Incomelist) getCurrentSession().merge(
					detachedInstance);
			log.debug("merge successful");
			return result;
		} catch (RuntimeException re) {
			log.error("merge failed", re);
			throw re;
		}
	}

	public void attachDirty(Incomelist instance) {
		log.debug("attaching dirty Incomelist instance");
		try {
			getCurrentSession().saveOrUpdate(instance);
			log.debug("attach successful");
		} catch (RuntimeException re) {
			log.error("attach failed", re);
			throw re;
		}
	}

	public void attachClean(Incomelist instance) {
		log.debug("attaching clean Incomelist instance");
		try {
			getCurrentSession().buildLockRequest(LockOptions.NONE).lock(
					instance);
			log.debug("attach successful");
		} catch (RuntimeException re) {
			log.error("attach failed", re);
			throw re;
		}
	}

	public static IncomelistDAO getFromApplicationContext(ApplicationContext ctx) {
		return (IncomelistDAO) ctx.getBean("IncomelistDAO");
	}
	
	/**
	 * 
	 * @param day  0:当天
	 * @return
	 */
	public List findLastDayList(Integer day) {

		log.debug("finding all Service instances");
		try {
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			 Calendar todayStart = Calendar.getInstance(); 
			 todayStart.add(Calendar.DAY_OF_MONTH,-day);  
			 
			 todayStart.set(Calendar.AM_PM,0);
		        todayStart.set(Calendar.HOUR, 0);  
		        todayStart.set(Calendar.MINUTE, 0);  
		        todayStart.set(Calendar.SECOND, 0);  
		     
			Date todayTime = todayStart.getTime();  
			
			String queryString = "from Incomelist u where u.itime >=:date order by u.itime desc";
//			String queryString = "from User";
			Query queryObject = getCurrentSession().createQuery(queryString);
			queryObject.setTimestamp("date", todayTime);
//			queryObject.setTimestamp("beginDate", todayTime);
			return queryObject.list();
		} catch (RuntimeException re) {
			log.error("find all failed", re);
			throw re;
		}
	}
	
	public List findUserIncomeByPage(Integer page, Integer size,Integer uid) {
		String queryString;
		Query q ;
		try {
			 queryString = "from Incomelist   msg where msg.account.aid = "+uid+" order by msg.itime desc";
			 q = getCurrentSession().createQuery(queryString);
			q.setFirstResult(page*size);
			q.setMaxResults(size);
			return q.list();
		} catch (RuntimeException re) {
			log.error("find all failed", re);
			throw re;
		}
	}
}